package com.xxl.job.admin.api.interceptor;

import cn.hutool.crypto.SecureUtil;
import com.xxl.job.admin.api.utils.AppSignUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Objects;

/**
 * 校验请求
 */
@Component
public class CsrfCheck {

    /**
     * 校验签名
     * @param timestamp
     * @param sign
     * @return
     */
    public boolean checkSign(String appSecret, String timestamp,String sign){
        if(StringUtils.isBlank(timestamp) || StringUtils.isBlank(sign)){
            return false;
        }
        String sign1 = AppSignUtil.sign(appSecret, timestamp);
        return Objects.equals(sign1,sign);
    }

    /**
     * 获取签名
     * @param times 时间戳
     * @return
     */
    public static String sign(String appSecret,String times){
        try{
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec key = new SecretKeySpec(appSecret.getBytes(), "HmacSHA256");
            mac.init(key);
            return SecureUtil.md5(Arrays.toString(mac.doFinal(times.getBytes())));
        }catch (NoSuchAlgorithmException | InvalidKeyException e){
            throw new RuntimeException("sign api secret failed", e);
        }
    }
}
